﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyTruongHoc_App.MyDataSet;
using QuanLyTruongHoc_App.MyDataSet.QLTHTableAdapters;
using System.IO;

namespace QuanLyTruongHoc_App
{
    public partial class DangKy : Form
    {
        public const String REG_FILE = "dkss.sys";

        public delegate void RegDone(object sender);
        public event RegDone Registered;

        private Boolean wasSave;
        private MyDataSet.QLTH.tbl_ThongTinNhaTruongDataTable thongTin;
        private tbl_ThongTinNhaTruongTableAdapter adap;
        private String filePath = "";

        public DangKy()
        {
            InitializeComponent();
        }

        public static Boolean checkDangKy()
        {
            String fileName = Application.StartupPath + "\\" + REG_FILE;
            if (!File.Exists(fileName))
                return false;

            System.IO.StreamReader reader = new StreamReader(fileName);
            try
            {
                String ma = "";
                for (int i = 0; i < 6; i++)
                {
                    String temp = reader.ReadLine();
                    ma += getMyCode(temp);
                }

                String c = reader.ReadLine();
                reader.Close();
                return (ma == c);
            }
            catch (Exception)
            {
                try { reader.Close(); }
                catch { }

                return false;
            }
        }

        private void checkUserPower()
        {
            if (!checkDangKy()) return;

            int pow;
            if (PublicLib.CURR_USER.Length > 0)
                pow = PublicLib.getUserPower(PConst.QUYEN_THAY_THONG_TIN);
            else
                pow = 0;

            // user co quyen view
            /*if (!((pow & PConst.POW_VIEW) > 0))
            {
                MessageBox.Show(MSG.MSG_KHONG_DU_QUYEN);
                this.Close();
            }*/
            // user co quyen them
            //tsb_TaoMoi.Enabled = ((pow & PConst.POW_ADD) > 0);

            // user co quyen edit
            tsb_Luu.Enabled = 
               bt_DoiAnh.Enabled = ((pow & PConst.POW_EDIT) > 0);
            tb_TenTruong.ReadOnly = tb_DiaChi.ReadOnly = tb_DienThoai.ReadOnly =
                tb_Email.ReadOnly = tb_Fax.ReadOnly = tb_Website.ReadOnly = 
                    tb_MaDangKy.ReadOnly = !((pow & PConst.POW_EDIT) > 0);

            // user co delete
            //dg_DanhSach.AllowUserToDeleteRows =
            //    tsb_Delete.Enabled = ((pow & PConst.POW_DEL) > 0);
        }

        private void QLHinhThucCanBo_Load(object sender, EventArgs e)
        {
            loadData();
        }

        private void loadData()
        {
            thongTin = new QLTH.tbl_ThongTinNhaTruongDataTable();
            adap = new tbl_ThongTinNhaTruongTableAdapter();
            adap.Connection.ConnectionString = PublicLib.getStrConn();

            adap.Fill(thongTin);
            if (thongTin.Rows.Count > 0)
            {
                tb_TenTruong.Text = CryptorEngine.Decrypt(thongTin[0][thongTin.TenTruongColumn].ToString(), true);
                tb_DiaChi.Text = CryptorEngine.Decrypt(thongTin[0][thongTin.DiaChiColumn].ToString(), true);
                tb_DienThoai.Text = CryptorEngine.Decrypt(thongTin[0][thongTin.DienThoaiColumn].ToString(), true);
                tb_Fax.Text = CryptorEngine.Decrypt(thongTin[0][thongTin.FaxColumn].ToString(), true);
                tb_Website.Text = CryptorEngine.Decrypt(thongTin[0][thongTin.emailColumn].ToString(), true);
                tb_Email.Text = CryptorEngine.Decrypt(thongTin[0][thongTin.websiteColumn].ToString(), true);

                // image
                if (!(thongTin[0][thongTin.logoColumn] == DBNull.Value))
                {
                    filePath = System.IO.Path.GetTempFileName();
                    FileStream fs = new System.IO.FileStream(filePath, FileMode.Create, FileAccess.Write);
                    Byte[] str = (byte[])thongTin[0][thongTin.logoColumn];
                    fs.Write(str, 0, str.Length);
                    fs.Close();

                    pb_Anh.Load(filePath);
                }
                else
                    filePath = "";
            }
            wasSave = true;
        }

        private static String getMyCode(String _input) 
        {
            String t = _input;
            String result = System.Math.Abs(t.GetHashCode()).ToString();
            if (result.Length > 4)
                return result.Substring(0, 4);
            else
                return result;
        }

        private Boolean checkVailidReg()
        {
            String ma = "";
            ma += getMyCode(tb_TenTruong.Text);
            ma += getMyCode(tb_DiaChi.Text);
            ma += getMyCode(tb_DienThoai.Text);
            ma += getMyCode(tb_Fax.Text);
            ma += getMyCode(tb_Website.Text);
            ma += getMyCode(tb_Email.Text);

            return (ma == tb_MaDangKy.Text);
        }

        private void saveData()
        {
            if (!checkVailidReg())
            {
                MessageBox.Show("Mã đăng ký chưa đúng.");
                return;
            }

            // save file
            try
            {
                System.IO.StreamWriter writer = new StreamWriter(Application.StartupPath + "\\" + REG_FILE);
                writer.WriteLine(tb_TenTruong.Text);
                writer.WriteLine(tb_DiaChi.Text);
                writer.WriteLine(tb_DienThoai.Text);
                writer.WriteLine(tb_Fax.Text);
                writer.WriteLine(tb_Website.Text);
                writer.WriteLine(tb_Email.Text);
                writer.WriteLine(tb_MaDangKy.Text);
                writer.Close();
            }
            catch 
            {
                MessageBox.Show("Có lỗi xảy ra trong quá trình đăng ký\nXin hãy thử lại!", "Thong Bao");
                return;
            }

            if (thongTin.Rows.Count > 0)
            {
                thongTin[0][thongTin.TenTruongColumn] = CryptorEngine.Encrypt(tb_TenTruong.Text, true);
                thongTin[0][thongTin.DiaChiColumn] = CryptorEngine.Encrypt(tb_DiaChi.Text, true);
                thongTin[0][thongTin.DienThoaiColumn] = CryptorEngine.Encrypt(tb_DienThoai.Text, true);
                thongTin[0][thongTin.FaxColumn] = CryptorEngine.Encrypt(tb_Fax.Text, true);
                thongTin[0][thongTin.websiteColumn] = CryptorEngine.Encrypt(tb_Website.Text, true);
                thongTin[0][thongTin.emailColumn] = CryptorEngine.Encrypt(tb_Email.Text, true);

                // image
                if (filePath.Length > 0)
                {
                    FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);
                    FileInfo fi = new FileInfo(filePath);
                    byte[] str = new byte[fi.Length];
                    long byteread = fs.Read(str, 0, (int)fi.Length);
                    thongTin[0][thongTin.logoColumn] = str;
                }
                else
                    thongTin[0][thongTin.logoColumn] = DBNull.Value;
            }
            else
            {
                DataRow nRow = thongTin.NewRow();

                nRow[thongTin.idColumn] = 1;
                nRow[thongTin.TenTruongColumn] = CryptorEngine.Encrypt(tb_TenTruong.Text, true);
                nRow[thongTin.DiaChiColumn] = CryptorEngine.Encrypt(tb_DiaChi.Text, true);
                nRow[thongTin.DienThoaiColumn] = CryptorEngine.Encrypt(tb_DienThoai.Text, true);
                nRow[thongTin.FaxColumn] = CryptorEngine.Encrypt(tb_Fax.Text, true);
                nRow[thongTin.websiteColumn] = CryptorEngine.Encrypt(tb_Website.Text, true);
                nRow[thongTin.emailColumn] = CryptorEngine.Encrypt(tb_Email.Text, true);

                // image
                if (filePath.Length > 0)
                {
                    FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);
                    FileInfo fi = new FileInfo(filePath);
                    byte[] str = new byte[fi.Length];
                    long byteread = fs.Read(str, 0, (int)fi.Length);
                    nRow[thongTin.logoColumn] = str;
                }
                else
                    nRow[thongTin.logoColumn] = DBNull.Value;

                thongTin.Rows.Add(nRow);
            }

            adap.Update(thongTin);
            wasSave = true;

            try
            {
                Registered(this);
                //this.Close()
                MessageBox.Show("Đã đăng ký thành công!");
            }
            catch { }
            
        }

        private void QLDanhGia_Resize(object sender, EventArgs e)
        {
            //dg_DanhSach.Height = stt_bottom.Top - dg_DanhSach.Top - 2;
            //dg_DanhSach.Width = this.Width - 5;
        }

        private void tsb_Luu_Click(object sender, EventArgs e)
        {
            saveData();           
        }

        private void PhanQuyen_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!wasSave)
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
        }

        private void tb_DoiAnh_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "JPG, JPEG FILE (*.jpg, *.jpeg)|*.jpg;*.jpeg";
            dialog.Multiselect = false;
            dialog.ShowDialog();

            filePath = dialog.FileName;

            if (filePath == "")
                return;
            FileInfo fi = new FileInfo(filePath);
            if (fi.Length > PConst.MAX_IMG_SIZE)
            {
                MessageBox.Show(MSG.MSG_IMAGE_TOO_BIG);
                filePath = "";
                return;
            }

            pb_Anh.Load(filePath);
            wasSave = false;
        }

        private void tb_TenTruong_TextChanged(object sender, EventArgs e)
        {
            wasSave = false;
        }

        private void DangKy_Activated(object sender, EventArgs e)
        {
            checkUserPower();
        }
    }
}
